package com.gzsz.util;

import java.sql.*;

public class DBUtil {
    /*
     * 执行返回连接对象
     * @return
     * */

    public Connection getConnection(){
        Connection connection=null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/medicald?serverTimezone=Asia/Shanghai";//修改为自己的数据库名字
            String dbUser = "root";
            String dbPassword = "123456";
            connection = DriverManager.getConnection(url, dbUser, dbPassword);

        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }
        return  connection;
    }

    /*
     * 执行查询方法
     * @param sql 要查询的SQL语句
     * @return 返回查询的结果类
     * */
    public ResultSet queryBySQL(String sql){
        ResultSet resultSet=null;
        Connection connection=getConnection();
        try {
            Statement statement= connection.createStatement();
            resultSet=statement.executeQuery(sql);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return resultSet;
    }

    /*
     * 执行 删除/修改/添加
     * @param sql  删除/修改/添加 的SQL语句
     * @return  受影响的行数
     * */
    public int executeUpdateBySQL(String sql){
        int i=0;
        Connection connection=getConnection();
        try {
            Statement statement=connection.createStatement();
            i=statement.executeUpdate(sql);
            statement.close();
            connection.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return i;

    }
}

